package com.zwb.demo.easyweb.modules.config.service.impl;

import com.zwb.demo.easyweb.common.entity.response.CommonCode;
import com.zwb.demo.easyweb.common.entity.response.ResponseResult;
import com.zwb.demo.easyweb.core.exception.ExceptionCast;
import com.zwb.demo.easyweb.core.utils.ConvertUtils;
import com.zwb.demo.easyweb.modules.config.entity.FormComponentPO;
import com.zwb.demo.easyweb.modules.config.repository.FormComponentPORepository;
import com.zwb.demo.easyweb.modules.config.service.FormComponentService;
import com.zwb.demo.easyweb.modules.config.vo.FormComponentVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class FormComponentServiceImpl implements FormComponentService {
    private final FormComponentPORepository formComponentRepository;

    @Autowired
    public FormComponentServiceImpl(FormComponentPORepository formComponentRepository) {
        this.formComponentRepository = formComponentRepository;
    }

    @Override
    public ResponseResult addOrUpdateOne(FormComponentVO vo) {
        if (StringUtils.isNotBlank(vo.getId())) {
            Optional<FormComponentPO> optional = formComponentRepository.findById(vo.getId());
            if (!optional.isPresent()) {
                ExceptionCast.cast(CommonCode.ID_NO_EXITS);
            }
            FormComponentPO po = optional.get();
            BeanUtils.copyProperties(vo, po);
            formComponentRepository.save(po);
        } else {
            FormComponentPO po = ConvertUtils.convertObject(vo, FormComponentPO.class);
            formComponentRepository.save(po);
        }
        return ResponseResult.ok();
    }

    @Override
    public ResponseResult deleteOne(String uuid) {
        if (StringUtils.isBlank(uuid)) {
            ExceptionCast.cast(CommonCode.ILLEGAL_PARAM);
        }
        formComponentRepository.deleteById(uuid);
        return ResponseResult.ok();
    }

    @Override
    public ResponseResult findAll() {
        List<FormComponentPO> allPO = formComponentRepository.findAll();
        List<FormComponentVO> allVO = ConvertUtils.convertList(allPO, FormComponentVO.class);
        return ResponseResult.ok().body(allVO);
    }
}
